package com.whmskj.xjlhbc.mobile.schedule;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.db.DataSourceType;
import com.whmskj.xjlhbc.db.DynamicDataSourceContextHolder;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.mapper.*;
import com.whmskj.xjlhbc.mobile.GetStartDate;
import com.whmskj.xjlhbc.service.IMesjzkService;
import com.whmskj.xjlhbc.service.IStatisticsDayJsService;
import com.whmskj.xjlhbc.service.IStatisticsDayZjService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MesRundataInfoTask {

    @Autowired
    private ScglMapper scglMapper;

    @Autowired
    private ScjzkMapper scjzkMapper;

    @Autowired
    private MesglMapper mesglMapper;

    @Autowired
    private MesjsjMapper mesjsjMapper;

    @Autowired
    private MeszjjMapper meszjjMapper;

    @Autowired
    private IMesjzkService mesjzkService;

    @Autowired
    private ScjsjMapper scjsjMapper;

    @Autowired
    private SckyzjjMapper sckyzjjMapper;

    @Autowired
    private SchfzjjMapper schfzjjMapper;

    @Autowired
    private MeszjjLzMapper meszjjLzMapper;

    @Autowired
    private MesjsjLzMapper mesjsjLzMapper;

    @Autowired
    private IStatisticsDayJsService statisticsDayJsService;

    @Autowired
    private IStatisticsDayZjService statisticsDayZjService;

    private static final String HF = "华方";
    private static final String KY = "开元";

    /**
     * 整经机,浆纱机
     */
//    @Scheduled(cron = "0 0/10 * * * ?")
    public void save(){
        try{
            String startDate = GetStartDate.getDayStartDate();
            String now = startDate.substring(0,10);
            List<String> jsjList = Arrays.asList("01", "02"); //浆纱机
            List<String> hfzjjList = Arrays.asList("01", "02", "03", "04");//整经机
            List<String> kyzjjList = Arrays.asList("05", "06");//整经机
            List<StatisticsDayJs> statisticsDayJsList = new ArrayList<>();
            List<StatisticsDayZj> statisticsDayZjList = new ArrayList<>();

            LambdaQueryWrapper<MesjsjLz> mesjsjLzLambdaQueryWrapper = new LambdaQueryWrapper<>();
            mesjsjLzLambdaQueryWrapper.ge(MesjsjLz::getTs, startDate).ge(MesjsjLz::getCurrentvalue,100);
            List<MesjsjLz> mesjsjLzList = mesjsjLzMapper.selectList(mesjsjLzLambdaQueryWrapper);

            LambdaQueryWrapper<MeszjjLz> meszjjLzLambdaQueryWrapper = new LambdaQueryWrapper<>();
            meszjjLzLambdaQueryWrapper.ge(MeszjjLz::getTs, startDate).ge(MeszjjLz::getCurrentvalue,100);
            List<MeszjjLz> meszjjLzList = meszjjLzMapper.selectList(meszjjLzLambdaQueryWrapper);
            jsjList.forEach(jsjMacId -> {
                List<MesjsjLz> list = mesjsjLzList.stream().filter(f -> f.getMacid().equals(jsjMacId)).collect(Collectors.toList());
                // 使用BigDecimal的longValue()方法转换
                long sum = list.stream().mapToLong(m -> m.getCurrentvalue().longValue()).sum();
                int zs = list.size();
                LambdaQueryWrapper<StatisticsDayJs> statisticsDayJsLambdaQueryWrapper = new LambdaQueryWrapper<>();
                statisticsDayJsLambdaQueryWrapper.eq(StatisticsDayJs::getMacid,jsjMacId).eq(StatisticsDayJs::getDateymd,now).last("limit 1");
                StatisticsDayJs statisticsDay = Optional.ofNullable(statisticsDayJsService.getOne(statisticsDayJsLambdaQueryWrapper)).orElseGet(StatisticsDayJs::new);
                statisticsDay.setMacid(jsjMacId);
                statisticsDay.setDateymd(now);
                statisticsDay.setZs(String.valueOf(zs));
                statisticsDay.setClothlength(String.valueOf(sum));
                statisticsDay.setUpdatetime(new Date());
                statisticsDayJsList.add(statisticsDay);
            });

            hfzjjList.forEach(zjjMacId -> {
                List<MeszjjLz> list = meszjjLzList.stream().filter(f -> f.getMacid().equals(zjjMacId)).collect(Collectors.toList());
                long sum = list.stream().mapToLong(m -> NumberUtil.parseLong(m.getCurrentvalue(), 0L)).sum();
                int zs = list.size();
                MeszjjLz meszjjLz = meszjjLzList.stream().filter(f -> f.getMacid().equals(zjjMacId)).findFirst().orElseGet(MeszjjLz::new);
                LambdaQueryWrapper<StatisticsDayZj> statisticsDayZjLambdaQueryWrapper = new LambdaQueryWrapper<>();
                statisticsDayZjLambdaQueryWrapper.eq(StatisticsDayZj::getMacid,zjjMacId).eq(StatisticsDayZj::getDateymd,now).last("limit 1");
                StatisticsDayZj statisticsDay = Optional.ofNullable(statisticsDayZjService.getOne(statisticsDayZjLambdaQueryWrapper)).orElseGet(StatisticsDayZj::new);
                statisticsDay.setMacid(zjjMacId);
                statisticsDay.setMacname("整经机");
                statisticsDay.setCs(HF);
                statisticsDay.setClassname(meszjjLz.getClassname());
                statisticsDay.setZs(String.valueOf(zs));
                statisticsDay.setDateymd(now);
                statisticsDay.setClothlength(String.valueOf(sum));
                statisticsDay.setUpdatetime(new Date());
                statisticsDayZjList.add(statisticsDay);
            });

            kyzjjList.forEach(zjjMacId -> {
                List<MeszjjLz> list = meszjjLzList.stream().filter(f -> f.getMacid().equals(zjjMacId)).collect(Collectors.toList());
                long sum = list.stream().mapToLong(m -> NumberUtil.parseLong(m.getCurrentvalue(), 0L)).sum();
                int zs = list.size();
                MeszjjLz meszjjLz = meszjjLzList.stream().filter(f -> f.getMacid().equals(zjjMacId)).findFirst().orElseGet(MeszjjLz::new);
                LambdaQueryWrapper<StatisticsDayZj> statisticsDayZjLambdaQueryWrapper = new LambdaQueryWrapper<>();
                statisticsDayZjLambdaQueryWrapper.eq(StatisticsDayZj::getMacid,zjjMacId).eq(StatisticsDayZj::getDateymd,now).last("limit 1");
                StatisticsDayZj statisticsDay = Optional.ofNullable(statisticsDayZjService.getOne(statisticsDayZjLambdaQueryWrapper)).orElseGet(StatisticsDayZj::new);
                statisticsDay.setMacid(zjjMacId);
                statisticsDay.setMacname("整经机");
                statisticsDay.setCs(KY);
                statisticsDay.setClassname(meszjjLz.getClassname());
                statisticsDay.setZs(String.valueOf(zs));
                statisticsDay.setDateymd(now);
                statisticsDay.setClothlength(String.valueOf(sum));
                statisticsDay.setUpdatetime(new Date());
                statisticsDayZjList.add(statisticsDay);
            });
            statisticsDayJsService.saveOrUpdateBatch(statisticsDayJsList);
            statisticsDayZjService.saveOrUpdateBatch(statisticsDayZjList);
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 整经机,浆纱机,锅炉,经轴库
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void save1(){
        try{
            List<String> glList = Arrays.asList("01", "02"); //锅炉
            List<String> jsjList = Arrays.asList("01", "02"); //浆纱机
            List<String> hfzjjList = Arrays.asList("01", "02", "03", "04");//整经机
            List<String> kyzjjList = Arrays.asList("05", "06");//整经机

            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SC.name());
            LambdaQueryWrapper<Scgl> scglLambdaQueryWrapper = new LambdaQueryWrapper<>();
            scglLambdaQueryWrapper.in(Scgl::getDevice, glList).orderByDesc(Scgl::getId).last("limit "+glList.size());
            List<Scgl> scglList = scglMapper.selectList(scglLambdaQueryWrapper);
            List<Scjsj> scjsjList = jsjList.stream().map(device->{
                LambdaQueryWrapper<Scjsj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Scjsj::getDevice, device).orderByDesc(Scjsj::getId).last("limit 1");
                return scjsjMapper.selectOne(wrapper);
            }).filter(Objects::nonNull).collect(Collectors.toList());
            List<Schfzjj> schfzjjList = hfzjjList.stream().map(device->{
                LambdaQueryWrapper<Schfzjj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Schfzjj::getDevice, device).orderByDesc(Schfzjj::getId).last("limit 1");
                return schfzjjMapper.selectOne(wrapper);
            }).filter(Objects::nonNull).collect(Collectors.toList());
            List<Sckyzjj> sckyzjjList = kyzjjList.stream().map(device->{
                LambdaQueryWrapper<Sckyzjj> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Sckyzjj::getDevice, device).orderByDesc(Sckyzjj::getId).last("limit 1");
                return sckyzjjMapper.selectOne(wrapper);
            }).filter(Objects::nonNull).collect(Collectors.toList());
            sckyzjjList.removeIf(Objects::isNull);

            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
            scglList.forEach(item -> {
                LambdaQueryWrapper<Mesgl> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Mesgl::getMacid, item.getDevice()).last("limit 1");
                Mesgl entity = Optional.ofNullable(mesglMapper.selectOne(queryWrapper)).orElseGet(Mesgl::new);
                Long id = entity.getId();
                BeanUtils.copyProperties(item, entity);
                entity.setId(id);
                entity.setMacid(item.getDevice());
                entity.setMacname("锅炉");
                int result = Objects.isNull(id) ? mesglMapper.insert(entity) : mesglMapper.updateById(entity);
            });
            scjsjList.forEach(item -> {
                LambdaQueryWrapper<Mesjsj> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Mesjsj::getMacid, item.getDevice()).last("limit 1");
                Mesjsj entity = Optional.ofNullable(mesjsjMapper.selectOne(queryWrapper)).orElseGet(Mesjsj::new);
                String entityA301 = entity.getA727();
                String itemA301 = item.getA727();
                long value1 = NumberUtil.parseLong(entityA301, 0L);
                long value2 = NumberUtil.parseLong(itemA301, 0L);
                if(value2<value1){
                    addJsjlz(entity);
                }
                Long id = entity.getId();
                BeanUtils.copyProperties(item, entity);
                entity.setId(id);
                entity.setMacid(item.getDevice());
                entity.setMacname("浆纱机");
                int result = Objects.isNull(id) ? mesjsjMapper.insert(entity) : mesjsjMapper.updateById(entity);
            });
            schfzjjList.forEach(item -> {
                LambdaQueryWrapper<Meszjj> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Meszjj::getMacid, item.getDevice()).last("limit 1");
                Meszjj entity = Optional.ofNullable(meszjjMapper.selectOne(queryWrapper)).orElseGet(Meszjj::new);
                String entityA301 = entity.getA301();
                String itemA301 = item.getA301();
                long value1 = NumberUtil.parseLong(entityA301, 0L);
                long value2 = NumberUtil.parseLong(itemA301, 0L);
                if(value2<value1){
                    addZjjlz(entity);
                }
                Long id = entity.getId();
                BeanUtils.copyProperties(item, entity);
                entity.setId(id);
                entity.setCs(HF);
                entity.setA291(item.getA302());
                entity.setA393(item.getA319());
                entity.setMacid(item.getDevice());
                entity.setMacname("整经机");
                int result = Objects.isNull(id) ? meszjjMapper.insert(entity) : meszjjMapper.updateById(entity);
            });

            sckyzjjList.forEach(item -> {
                LambdaQueryWrapper<Meszjj> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Meszjj::getMacid, item.getDevice()).last("limit 1");
                Meszjj entity = Optional.ofNullable(meszjjMapper.selectOne(queryWrapper)).orElseGet(Meszjj::new);
                String entityA301 = entity.getA301();
                String itemA301 = item.getA386();
                long value1 = NumberUtil.parseLong(entityA301, 0L);
                long value2 = NumberUtil.parseLong(itemA301, 0L);
                if(value2<value1){
                    addZjjlz(entity);
                }
                Long id = entity.getId();
                entity.setA291(item.getA398());
                entity.setA296(item.getA394());
                entity.setA301(item.getA386());
                entity.setA303(item.getA385());
                entity.setA305(item.getA387());
                entity.setA306(item.getA388());
                entity.setA307(item.getA391());
                entity.setA319(item.getA393());
                entity.setA393(item.getA393());
                entity.setTs(item.getTs());
                entity.setId(id);
                entity.setCs(KY);
                entity.setMacid(item.getDevice());
                entity.setMacname("整经机");
                int result = Objects.isNull(id) ? meszjjMapper.insert(entity) : meszjjMapper.updateById(entity);
            });
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 经轴库
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void saveJzk(){
        try{
            List<String> jzkList = Arrays.asList("01", "02"); //经轴库
            List<Mesjzk> mesjzkListAll = new ArrayList<>();
            jzkList.forEach(item -> {
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SC.name());
                List<Scjzk> scjzkList = scjzkMapper.queryListByDevice(item);
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
                List<String> list = scjzkList.stream().map(Scjzk::getZwh).collect(Collectors.toList());
                if(list.isEmpty())return;
                LambdaQueryWrapper<Mesjzk> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Mesjzk::getMacid, item).in(Mesjzk::getZwh, list);
                List<Mesjzk> queryMesjzkList = mesjzkService.list(queryWrapper);
                List<Mesjzk> mesjzkList = scjzkList.stream().map(jzk -> {
                    Mesjzk entity = queryMesjzkList.stream().filter(mesjzk -> mesjzk.getZwh().equals(jzk.getZwh())).findFirst().orElseGet(Mesjzk::new);
                    Long id = entity.getId();
                    BeanUtils.copyProperties(jzk, entity);
                    entity.setId(id);
                    entity.setMacid(jzk.getDevice());
                    entity.setMacname("经轴库");
                    return entity;
                }).collect(Collectors.toList());
                mesjzkListAll.addAll(mesjzkList);
            });
            mesjzkService.saveOrUpdateBatch(mesjzkListAll);
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    private void addZjjlz(Meszjj entity){
        MeszjjLz meszjjLz = new MeszjjLz();
        BeanUtils.copyProperties(entity, meszjjLz);
        meszjjLz.setCurrentvalue(entity.getA301());
        meszjjLz.setDateymd(DateUtil.today());
        meszjjLz.setClassname(entity.getA307());
        meszjjLz.setZs("1");
        meszjjLz.setId(null);
        meszjjLzMapper.insert(meszjjLz);
    }

    private void addJsjlz(Mesjsj entity){
        MesjsjLz mesjsjLz = new MesjsjLz();
        BeanUtils.copyProperties(entity, mesjsjLz);
        // 将String类型转换为BigDecimal类型
        mesjsjLz.setCurrentvalue(new BigDecimal(entity.getA727()));
        mesjsjLz.setDateymd(DateUtil.today());
        mesjsjLz.setId(null);
        mesjsjLzMapper.insert(mesjsjLz);
    }


}
